package com.sky.controller.admin;

import com.sky.constant.MessageConstant;
import com.sky.exception.BaseException;
import com.sky.result.Result;
import com.sky.utils.AliOssUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * 通用接口
 */
@RestController
@RequestMapping("/admin/common")
@Api(tags = "通用接口")
@Slf4j
public class CommonController {

    @Autowired
    AliOssUtil aliOssUtil;


    @PostMapping("/upload")
    @ApiOperation("上传图片")
    public Result<String> upload(MultipartFile file) {
        String fileName = UUID.randomUUID().toString();
        String originalFilename = file.getOriginalFilename();
        log.info("员工上传图片,原始文件名{}", originalFilename);
        int lastIndexOf = originalFilename.lastIndexOf(".");
        String type = originalFilename.substring(lastIndexOf);
        log.info("员工上传图片,上传OSS图片的路径{}", fileName + type);
        try {
            String url = aliOssUtil.upload(file.getBytes(), fileName + type);
            log.info("员工上传图片,阿里返回的图片的路径{}", fileName + type);
            return Result.success(url);
        } catch (IOException e) {
            throw new BaseException(MessageConstant.UPLOAD_FAILED);
        }

    }
}
